package site.security;

import site.util.CommonUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 */
public class AesCryptor {
    private String key = "29D50EB334B3E06B";
    private SecretKey secretKey;
    private Cipher c;
    private byte[] cipherByte;

    public AesCryptor() throws Exception {
        secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        c = Cipher.getInstance("AES");
    }

    public String encrypt(String str) throws Exception {
        c.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] src = str.getBytes("UTF-8");
        cipherByte = c.doFinal(src);
        return CommonUtils.toBase64(cipherByte);
    }

    public String decrypt(String str) throws Exception {
        byte[] buff = CommonUtils.fromBase64(str);
        c.init(Cipher.DECRYPT_MODE, secretKey);
        cipherByte = c.doFinal(buff);
        return new String(cipherByte, "UTF-8");
    }
}
